package com.jc.upload.aliyun.oos;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

public class AliyunOssUtil {

	private static final Logger logger = LoggerFactory.getLogger(AliyunOssUtil.class);
	
	private String publicImageBaseUrl="prod/" ;
	private String endpoint = "oss-cn-shenzhen.aliyuncs.com";
	private String accessKeyId = "LTAIBmZJvN1W00cj";
	private String accessKeySecret = "JQPVcob08OC9zbTBT8xCgvIPSlcgbG";
	private String bucketName = "jingxi";
	private String dir = "jc/prod/";
	private OSS oss;
	
	ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
	public void init() {
		conf.setIdleConnectionTime(2000);
		oss = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret,conf);
	}

	/**
	 * 销毁
	 */
	public void destory() {
		oss.shutdown();
	}

	public String uploadImg2Oss(MultipartFile file) throws Exception {
		init();
		if (file.getSize() > 10 * 1024 * 1024) {
			throw new Exception("上传图片大小不能超过10M！");
		}
		String originalFilename = file.getOriginalFilename();
		String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
		Random random = new Random();
		String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
		try {
			InputStream inputStream = file.getInputStream();
			this.uploadFile2OSS(inputStream, name);
			return publicImageBaseUrl + name;
		} catch (Exception e) {
			throw new Exception("图片上传失败");
		}finally {
			destory();
		}
	}

	public String uploadImg2Oss(File file) throws Exception {
		
		init();
		if (file.length() > 3 * 1024 * 1024) {
			throw new Exception("上传图片大小不能超过3M！");
		}
		String originalFilename = file.getAbsolutePath();
		String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
		Random random = new Random();
		String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
		try {
			InputStream inputStream = new FileInputStream(file);
			this.uploadFile2OSS(inputStream, name);
			return publicImageBaseUrl + name;
		} catch (Exception e) {
			throw new Exception("图片上传失败");
		}finally {
			destory();
		}
		
	}
	
	/**
	 * 获得图片路径
	 *
	 * @param fileUrl
	 * @return
	 */
	public String getImgUrl(String fileUrl) {
		System.out.println(fileUrl);
		if (!StringUtils.isEmpty(fileUrl)) {
			String[] split = fileUrl.split("/");
			return this.getUrl(this.dir + split[split.length - 1]);
		}
		return null;
	}

	/**
	 * 上传到OSS服务器 如果同名文件会覆盖服务器上的
	 *
	 * @param instream 文件流
	 * @param fileName 文件名称 包括后缀名
	 * @return 出错返回"" ,唯一MD5数字签名
	 */
	public String uploadFile2OSS(InputStream instream, String fileName) {
		String ret = "";
		try {
			// 创建上传Object的Metadata
			ObjectMetadata objectMetadata = new ObjectMetadata();
			objectMetadata.setContentLength(instream.available());
			objectMetadata.setCacheControl("no-cache");
			objectMetadata.setHeader("Pragma", "no-cache");
			objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
			objectMetadata.setContentDisposition("inline;filename=" + fileName);
			// 上传文件
			PutObjectResult putResult = oss.putObject(bucketName, dir + fileName, instream, objectMetadata);
			ret = putResult.getETag();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			try {
				if (instream != null) {
					instream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}

	/**
	 * Description: 判断OSS服务文件上传时文件的contentType
	 * @param FilenameExtension 文件后缀
	 * @return String
	 */
	public static String getcontentType(String filenameExtension) {
		if (filenameExtension.equalsIgnoreCase("bmp")) {
			return "image/bmp";
		}
		if (filenameExtension.equalsIgnoreCase("gif")) {
			return "image/gif";
		}
		if (filenameExtension.equalsIgnoreCase("jpeg") || filenameExtension.equalsIgnoreCase("jpg")
				|| filenameExtension.equalsIgnoreCase("png")) {
			return "image/jpeg";
		}
		if (filenameExtension.equalsIgnoreCase("html")) {
			return "text/html";
		}
		if (filenameExtension.equalsIgnoreCase("txt")) {
			return "text/plain";
		}
		if (filenameExtension.equalsIgnoreCase("vsd")) {
			return "application/vnd.visio";
		}
		if (filenameExtension.equalsIgnoreCase("pptx") || filenameExtension.equalsIgnoreCase("ppt")) {
			return "application/vnd.ms-powerpoint";
		}
		if (filenameExtension.equalsIgnoreCase("docx") || filenameExtension.equalsIgnoreCase("doc")) {
			return "application/msword";
		}
		if (filenameExtension.equalsIgnoreCase("xml")) {
			return "text/xml";
		}
		return "image/jpeg";
	}

	/**
	 * 获得url链接
	 *
	 * @param key
	 * @return
	 */
	public String getUrl(String key) {
		// 设置URL过期时间为10年 3600l* 1000*24*365*10
		Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
		// 生成URL
		URL url = oss.generatePresignedUrl(bucketName, key, expiration);
		if (url != null) {
			return url.toString();
		}
		return null;
	}

	public static void main(String[] args) {

		AliyunOssUtil imp = new AliyunOssUtil();
		imp.init();
		File file = new File("D:\\111.jpg");
		//String name = UUID.randomUUID().toString().replaceAll("-", "");

		try {
			//FileInputStream in = new FileInputStream(file);
		    //String tag = imp.uploadFile2OSS(in, name + ".jpg");
			//System.out.println("http://video.pusai.net/jc/" + name + ".jpg" + "   ------------  " );
			
		    String name = imp.uploadImg2Oss(file);
		    String url = imp.publicImageBaseUrl + name;
		    
//		    String imgUrl = imp.getImgUrl(name);
//		    System.out.println(imgUrl);
//		    String[] split = imgUrl.split("\\?");
//		    for(String str : split) {
//			   System.out.println(str);
//		    }
	        
		   System.out.println("http://video.pusai.net/jc/prod/" + name);
		    

		} catch (Exception e) {
			e.printStackTrace();
		}



	}

}
